import { routes } from './routes.js'
import { useUserStore } from '@/store'

const install = () => {
    let _u = uni.$u
    const userStore = useUserStore()

    // 添加路由跳转权限控制
    for (let key in routes) {
        routes[key].to = (query: any, mode: string) => {
            // 校验路由是否存在
            let ro = routes[key]
            if (!ro) throw '没有找到对应路由'
            // 跳转登录页时，校验是否已经授权，则跳转默认页
            if (ro.path === '/pages/login/login' && userStore.token) {
                _u.route({
                    type: routes.home.mode || 'navigateTo',
                    url: routes.home.path
                })
                return
            }
            // 是否需要权限，并相应处理
            if (ro.requiresLogin) {
                if (userStore.token) {
                    // console.log('已登录，跳转指向页面',ro);
                    // 已登录，跳转指向页面
                    if (!ro.requiresAuth || (ro.requiresAuth && userStore.userInfo)) {
                        _u.route({
                            type: mode || ro.mode || 'navigateTo',
                            url: ro.path,
                            params: query ? query : {}
                        })
                    } else {
                        _u.route({
                            type: 'navigateTo',
                            url: routes.login.path,
                            animationType: 'slide-in-bottom'
                        })
                    }
                } else {
                    // 未登录，跳转登录页
                    _u.route({
                        type: mode || routes.login.mode || 'navigateTo',
                        url: routes.login.path,
                        animationType: 'slide-in-bottom'
                    })
                }
            } else {
                // 不需要登录的页面直接放过
                _u.route({
                    type: mode || ro.mode || 'navigateTo',
                    url: ro.path,
                    params: query ? query : {},
                    animationType: ro.animationType || 'pop-in'
                })
            }
        }
    }
    // 添加路由返回
    routes.back = (delta: number, animationType: any) => {
        uni.$u.route({
            type: 'navigateBack',
            delta: delta,
            animationType: animationType || 'pop-out'
        })
    }
    // 路由配置赋值
    uni.$u.$MRouter = routes
}

export default {
    install
}
